<template>
  <div class="morse-tool">
    <div class="tool-header">
      <h1>摩斯电码编码解码工具</h1>
      <p>快速进行摩斯电码编码和解码操作</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 输入区域 -->
        <el-col :span="12">
          <div class="input-section">
            <div class="section-header">
              <h3>输入内容</h3>
              <div class="actions">
                <el-button @click="clearInput" size="small">清空</el-button>
                <el-button @click="pasteFromClipboard" size="small" type="primary">粘贴</el-button>
              </div>
            </div>
            
            <el-input
              v-model="inputText"
              type="textarea"
              :rows="8"
              placeholder="请输入要编码或解码的文本..."
              @input="handleInput"
            />
            
            <div class="input-actions">
              <el-button 
                type="primary" 
                @click="encode"
                :disabled="!inputText.trim()"
                :loading="isProcessing"
              >
                <el-icon><Lock /></el-icon>
                摩斯编码
              </el-button>
              <el-button 
                type="success" 
                @click="decode"
                :disabled="!inputText.trim()"
                :loading="isProcessing"
              >
                <el-icon><Unlock /></el-icon>
                摩斯解码
              </el-button>
            </div>
          </div>
        </el-col>

        <!-- 输出区域 -->
        <el-col :span="12">
          <div class="output-section">
            <div class="section-header">
              <h3>处理结果</h3>
              <div class="actions">
                <el-button @click="copyResult" size="small" :disabled="!outputText">复制</el-button>
                <el-button @click="clearOutput" size="small">清空</el-button>
              </div>
            </div>
            
            <el-input
              v-model="outputText"
              type="textarea"
              :rows="8"
              placeholder="编码或解码的结果将显示在这里..."
              readonly
            />
            
            <div class="output-info" v-if="outputText">
              <el-tag type="info" size="small">
                长度: {{ outputText.length }} 字符
              </el-tag>
              <el-tag type="success" size="small" v-if="lastOperation">
                操作: {{ lastOperation }}
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 摩斯电码对照表 -->
      <div class="morse-table">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>摩斯电码对照表</span>
            </div>
          </template>
          
          <div class="morse-content">
            <div class="morse-section">
              <h4>字母</h4>
              <div class="morse-grid">
                <div class="morse-item" v-for="(code, letter) in morseAlphabet" :key="letter">
                  <span class="letter">{{ letter }}</span>
                  <span class="code">{{ code }}</span>
                </div>
              </div>
            </div>
            
            <div class="morse-section">
              <h4>数字</h4>
              <div class="morse-grid">
                <div class="morse-item" v-for="(code, digit) in morseNumbers" :key="digit">
                  <span class="letter">{{ digit }}</span>
                  <span class="code">{{ code }}</span>
                </div>
              </div>
            </div>
            
            <div class="morse-section">
              <h4>标点符号</h4>
              <div class="morse-grid">
                <div class="morse-item" v-for="(code, symbol) in morseSymbols" :key="symbol">
                  <span class="letter">{{ symbol }}</span>
                  <span class="code">{{ code }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 示例和说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>什么是摩斯电码？</h4>
            <p>摩斯电码（Morse Code）是一种时通时断的信号代码，通过不同的排列顺序来表达不同的英文字母、数字和标点符号。</p>
            
            <h4>编码规则：</h4>
            <ul>
              <li>短信号（点）：用 . 表示</li>
              <li>长信号（划）：用 - 表示</li>
              <li>字母间分隔：用空格表示</li>
              <li>单词间分隔：用 / 表示</li>
            </ul>
            
            <h4>使用场景：</h4>
            <ul>
              <li>无线电通信</li>
              <li>紧急求救信号（SOS）</li>
              <li>军事通信</li>
              <li>业余无线电爱好</li>
            </ul>
            
            <h4>示例：</h4>
            <div class="example">
              <p><strong>原文：</strong>HELLO</p>
              <p><strong>摩斯编码：</strong>.... . .-.. .-.. ---</p>
              <p><strong>求救信号：</strong>SOS = ... --- ...</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock, Unlock } from '@element-plus/icons-vue'

const inputText = ref('')
const outputText = ref('')
const isProcessing = ref(false)
const lastOperation = ref('')

// 摩斯电码对照表
const morseAlphabet = {
  'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
  'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
  'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
  'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
  'Y': '-.--', 'Z': '--..'
}

const morseNumbers = {
  '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
  '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.'
}

const morseSymbols = {
  '.': '.-.-.-', ',': '--..--', '?': '..--..', "'": '.----.', '!': '-.-.--',
  '/': '-..-.', '(': '-.--.', ')': '-.--.-', '&': '.-...', ':': '---...',
  ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-',
  '"': '.-..-.', '$': '...-..-', '@': '.--.-.'
}

const handleInput = () => {
  // 输入变化时的处理逻辑
}

const encode = async () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要编码的内容')
    return
  }
  
  isProcessing.value = true
  try {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const text = inputText.value.toUpperCase()
    let morseCode = ''
    
    for (let i = 0; i < text.length; i++) {
      const char = text[i]
      
      if (char === ' ') {
        morseCode += '/ '
      } else if (morseAlphabet[char]) {
        morseCode += morseAlphabet[char] + ' '
      } else if (morseNumbers[char]) {
        morseCode += morseNumbers[char] + ' '
      } else if (morseSymbols[char]) {
        morseCode += morseSymbols[char] + ' '
      } else {
        morseCode += char + ' '
      }
    }
    
    outputText.value = morseCode.trim()
    lastOperation.value = '摩斯编码'
    ElMessage.success('摩斯编码完成')
  } catch (error) {
    ElMessage.error('编码失败：' + error.message)
  } finally {
    isProcessing.value = false
  }
}

const decode = async () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要解码的内容')
    return
  }
  
  isProcessing.value = true
  try {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const morseCode = inputText.value.trim()
    const words = morseCode.split('/')
    let decodedText = ''
    
    for (const word of words) {
      const letters = word.trim().split(' ')
      let decodedWord = ''
      
      for (const letter of letters) {
        if (letter.trim()) {
          // 查找对应的字符
          const char = findCharByMorse(letter.trim())
          decodedWord += char
        }
      }
      
      decodedText += decodedWord + ' '
    }
    
    outputText.value = decodedText.trim()
    lastOperation.value = '摩斯解码'
    ElMessage.success('摩斯解码完成')
  } catch (error) {
    ElMessage.error('解码失败：' + error.message)
  } finally {
    isProcessing.value = false
  }
}

const findCharByMorse = (morse) => {
  // 查找字母
  for (const [char, code] of Object.entries(morseAlphabet)) {
    if (code === morse) return char
  }
  
  // 查找数字
  for (const [char, code] of Object.entries(morseNumbers)) {
    if (code === morse) return char
  }
  
  // 查找符号
  for (const [char, code] of Object.entries(morseSymbols)) {
    if (code === morse) return char
  }
  
  return '?'
}

const clearInput = () => {
  inputText.value = ''
  ElMessage.info('已清空输入内容')
}

const clearOutput = () => {
  outputText.value = ''
  lastOperation.value = ''
  ElMessage.info('已清空输出结果')
}

const copyResult = async () => {
  if (!outputText.value) {
    ElMessage.warning('没有可复制的内容')
    return
  }
  
  try {
    await navigator.clipboard.writeText(outputText.value)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = outputText.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

const pasteFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputText.value = text
    ElMessage.success('已粘贴内容')
  } catch (error) {
    ElMessage.error('无法访问剪贴板，请手动粘贴')
  }
}
</script>

<style scoped>
.morse-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.input-section,
.output-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.input-actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
}

.output-info {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.morse-table {
  margin: 40px 0;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.morse-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
}

.morse-section h4 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 1.1rem;
  border-bottom: 2px solid #667eea;
  padding-bottom: 5px;
}

.morse-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 8px;
}

.morse-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.letter {
  font-weight: bold;
  color: #333;
  font-size: 1.1rem;
  margin-bottom: 4px;
}

.code {
  font-family: 'Courier New', monospace;
  color: #667eea;
  font-size: 0.9rem;
}

.tool-info {
  margin-top: 40px;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.example {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.example p {
  margin: 5px 0;
  font-family: 'Courier New', monospace;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .input-actions {
    flex-direction: column;
  }
  
  .output-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .morse-content {
    grid-template-columns: 1fr;
  }
  
  .morse-grid {
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  }
}
</style>
